package main

import (
	"bytes"
	"flag"
	"go/format"
	"io/ioutil"
	"path/filepath"
	"strings"
	"text/template"

	"gitee.com/nggs/tools/code_generator"
	"gitee.com/nggs/tools/code_generator/golang"
	"gitee.com/nggs/tools/print"
)

var (
	flagDebug            = flag.Bool("debug", false, "debug mode, default is false")
	flagDir              = flag.String("d", ".", "analyse directory, default is .")
	flagTemplateFilePath = flag.String("t", "", "template file path, default is empty")
)

func main() {
	flag.Parse()

	print.SetDebugMode(*flagDebug)

	absAnalyzeDir, err := filepath.Abs(*flagDir)
	if err != nil {
		print.Panicf("get absolute analyze dir fail, %s", err)
	}

	var tpl *template.Template
	if *flagTemplateFilePath != "" {
		templateContent, err := ioutil.ReadFile(*flagTemplateFilePath)
		if err != nil {
			print.Panicf("read template file content fail, dir=%s, %s", *flagTemplateFilePath, err)
		}
		if golang.TemplateFunc != nil {
			tpl, err = template.New("gen_extend").Funcs(golang.TemplateFunc).Parse(string(templateContent))
		} else {
			tpl, err = template.New("gen_extend").Parse(string(templateContent))
		}
	} else {
		if golang.TemplateFunc != nil {
			tpl, err = template.New("gen_extend").Funcs(golang.TemplateFunc).Parse(DefaultTemplate)
		} else {
			tpl, err = template.New("gen_extend").Parse(DefaultTemplate)
		}
	}
	if err != nil {
		print.Panicf("%s", err)
	}

	var pkgInfo = code_generator.MustAnalyzeDir(absAnalyzeDir)

	for _, file := range pkgInfo.Files {
		var buffer bytes.Buffer
		err = tpl.Execute(&buffer, file)
		if err != nil {
			print.Panicf("execute template fail, file path=%s, %s", file.FilePath, err)
		}

		filePath := strings.TrimRight(file.FilePath, ".go")
		filePath += ".ex.go"

		bs := buffer.Bytes()
		bs, err = format.Source(buffer.Bytes())
		if err != nil {
			print.Panicf("format %s fail, %s\n%s", filePath, err, string(bs))
		}

		err = ioutil.WriteFile(filePath, bs, 0766)
		if err != nil {
			print.Panicf("write %s fail, %s", filePath, err)
		}

		print.Infof("-> %s", filePath)
	}
}
